package com.scedu.dao;

import com.scedu.domain.Student;
import com.scedu.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/*
Studentdao接口的jdbc实现类
 */
public class StudentDAOImpl implements StudentDAO {
    @Override
    public List<Student> query() {
        List<Student> students=new ArrayList<Student>();
        Connection connection=null;
        PreparedStatement prepareStatement=null;
        ResultSet resultSet=null;
        String sql="select * from tb_student";
        try {
           connection= JdbcUtil.getConnetcion();
            prepareStatement= connection.prepareStatement(sql);
            resultSet=prepareStatement.executeQuery();
            while (resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("name");
                Integer age=resultSet.getInt("age");
                Student student=new Student();
                student.setAge(age);
                student.setId(id);
                student.setName(name);
                students.add(student);
                System.out.println(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.release(resultSet,prepareStatement,connection);
        }
        return students;
    }

    @Override
    public void add(Student student) {
        Connection connection=null;
        PreparedStatement prepareStatement=null;
        ResultSet resultSet=null;
        String name=student.getName();
        Integer age=student.getAge();
        String sql="insert  into tb_student (name,age) value (?,?)";
        try {
            connection= JdbcUtil.getConnetcion();
            prepareStatement= connection.prepareStatement(sql);
            prepareStatement.setString(1,name);
            prepareStatement.setInt(2,age);
            prepareStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.release(resultSet,prepareStatement,connection);
        }
    }
}
